package com.bigData.main.service.impl;

import com.bigData.main.mapper.CarMapper;
import com.bigData.main.pojo.Car;
import com.bigData.main.service.CarService;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Service
public class CarServiceImpl implements CarService {

    @Resource
    private CarMapper carMapper;

    @Override
    public Integer insertacar(Car car) {
        return carMapper.insertCar(car);
    }

    @Override
    public Integer insertcar(Car car) {
        return carMapper.insertCarAll(car);
    }

    @Override
    public List<Car> selectAllCar(Car car) {
        return carMapper.selectAllCar();
    }

    @Override
    public List<Car> selectacar(int car) {
        return carMapper.selectCarById(car);
    }

    @Override
    public Integer updatecar(Car car) {
        return carMapper.updateCar(car);
    }

    public Integer updatecarstatus(int cid) {
        return carMapper.updateCarStatus(cid);
    }

    @Override
    public Integer deletecar(int cid) {
        return carMapper.deleteCar(cid);
    }

    @Override
    public List<Car> selectSoldCars() {
        return carMapper.selectSoldCars();
    }

    @Override
    public List<Car> selectUnsoldCars() {
        return carMapper.selectUnsoldCars();
    }

    public Integer countCreator(String creator) {
        return carMapper.countCreator(creator);
    }

    @Override
    public Integer allCar() {
        return carMapper.allCar();
    }

    @Override
    public Integer alluCar() {
        return carMapper.alluCar();
    }

    @Override
    public Integer allPrice() {
        return carMapper.allPrice();
    }

    @Override
    public Integer timeCount() {
        return carMapper.timeCount();
    }

    @Override
    public Integer batchInsertCars(List<Car> cars) {
        for (Car car : cars) {
            // 确保每个 car 对象的字段都被正确设置
            carMapper.insertCarAll(car);  // 调用插入单车方法
        }
        return cars.size();  // 返回插入的记录数
    }

    @Override
    public List<Car> parseFile(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (extension.equalsIgnoreCase("csv")) {
            return parseCSVFile(file);
        } else if (extension.equalsIgnoreCase("txt")) {
            return parseTXTFile(file);
        } else {
            throw new IllegalArgumentException("不支持的文件类型，请上传CSV或TXT文件。");
        }
    }

    private List<Car> parseCSVFile(MultipartFile file) {
        List<Car> cars = new ArrayList<>();
        try (CSVReader reader = new CSVReader(new InputStreamReader(file.getInputStream()))) {
            String[] nextLine;
            // 跳过文件头（如果有）
            reader.readNext(); // 读取标题行

            while ((nextLine = reader.readNext()) != null) {
                // 校验每行数据的字段数是否符合要求
                if (nextLine.length < 7) { // 确保字段数量足够
                    continue;
                }

                Car car = new Car();
                car.setCname(nextLine[0].trim());                     // cname
                car.setColor(nextLine[1].trim());                     // color
                car.setPrice(Integer.parseInt(nextLine[2].trim())); // price
                car.setStorage(nextLine[3].trim());                   // storage
                car.setStatus(nextLine[5].trim()); // status
                car.setCreator(nextLine[6].trim());                   // creator

                // 添加到列表
                cars.add(car);
            }
        } catch (CsvValidationException | IOException | NumberFormatException e) {
            throw new RuntimeException("CSV文件解析错误", e);
        }
        return cars;
    }

    private List<Car> parseTXTFile(MultipartFile file) {
        List<Car> cars = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 假设TXT文件的每一行格式为：ID: 829, 车名: 奔驰E级, 颜色: 深灰色, 价格: 1111111, 数量: 5, 存储地址: 仓库A, 时间: 2024-12-19, 状态: 已售出, 创建人: admin
                String[] parts = line.split(", ");
                if (parts.length < 9) {
                    continue; // 如果字段不足，跳过该行
                }

                Car car = new Car();
                car.setCname(parts[1].split(": ")[1].trim()); // 车名
                car.setColor(parts[2].split(": ")[1].trim()); // 颜色
                car.setPrice(Integer.parseInt(parts[3].split(": ")[1].trim())); // 价格
                car.setStorage(parts[4].split(": ")[1].trim()); // 存储地址
                car.setStatus(parts[6].split(": ")[1].trim()); // 存储地址
                car.setCreator(parts[7].split(": ")[1].trim()); // 创建人
                // 校验状态字段是否有效
                cars.add(car);
            }
        } catch (IOException | NumberFormatException e) {
            throw new RuntimeException("TXT文件解析错误", e);
        }
        return cars;
    }
}